import React, { useMemo, useState } from "react";
import { useEffect } from "react";
import { Input, Tree } from "antd";
import type { DataNode } from "antd/es/tree";
import { getAllData } from "./api/getAllData";
import { ResponseSearchDataType } from "./types/type";
import "antd/dist/antd.css";

const { Search } = Input; // 搜索的组件
const x = 3;
const y = 2;
const z = 1;
const defaultData: DataNode[] = [];
//1. 封装axios
//2. 接口
//3. 接口类型的约束
//4. 调用接口
//5. 结合tree组件
//6. 筛选(方法)

// 结合ts之后
// 1. 函数式组件 返回值 JSX.Element
// 2. useState<泛型参数> : 约束state的类型

const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};

export default function App(): JSX.Element {
  const [allData, setAllData] = useState<ResponseSearchDataType[]>([]);
  const [inputValue, setInputValue] = useState<string>("");

  // 扩展的key
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  // 自动展开的数据
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (newExpandedKeys: string[], info: any) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = allData
      .map((item) => {
        if (item.label.indexOf(value) > -1) {
          return getParentKey(item.key, allData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setInputValue(value);
    setAutoExpandParent(true);
  };

  const treeData = useMemo(() => {
    const loop = (data: ResponseSearchDataType[]): DataNode[] => {
      const result = data.map((item) => {
        const strTitle = item.label as string;
        const index = strTitle.indexOf(inputValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + inputValue.length);
        const title =
          index > -1 ? (
            <span>{strTitle}</span>
          ) : (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{inputValue}</span>
              {afterStr}
            </span>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });
      console.log(result);
      return result;
    };

    return loop(allData); // TODO
  }, [inputValue]);

  function handleSearch() {
    // 筛选数据
    dfs(allData[0]);
  }

  // 深度优先遍历
  function dfs(node: ResponseSearchDataType) {
    // stack: 数组有1项
    const stack = [node];
    while (stack.length > 0) {
      const first = stack.shift();
      if (first?.label.includes(inputValue)) {
        console.log(first);
      }
      // [2,5]  // [5,2]
      first?.children &&
        first?.children
          .slice()
          .reverse()
          .forEach((child) => {
            stack.unshift(child);
          });
    }
  }

  useEffect(() => {
    const loadData = async () => {
      const res = await getAllData();
      console.log(res);
      setAllData(res);
    };
    loadData();
  }, []);
  return (
    <div>
      {/* <input
        type="text"
        value={inputValue}
        onChange={(e) => {
          setInputValue(e.target.value);
        }}
      />
      <button onClick={handleSearch}>搜索</button> */}

      <Search
        style={{ marginBottom: 8 }}
        placeholder="Search"
        onChange={onChange}
      />
      <Tree
        // @ts-ignore
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        treeData={treeData}
      />
    </div>
  );
}
